//
//  main.c
//  Sparse matrix6
//
//  Created by zhuoooo on 2022/11/30.
//  Copyright © 2022年 zhuoooo. All rights reserved.
//  矩阵及其转置矩阵

#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 12500//假设非零元素个数的最大值为12500
#define OK 1
#define ERROR -1
typedef int ElemType;
typedef int Status;
typedef struct {
    int i, j;        //该非零元的行下表和列下表
    ElemType e;
}Triple;
typedef struct{
    Triple data[MAX_SIZE + 1];//非零元三元组表，data[0]未用
    int row, col, tn;//矩阵的行数、列数和非零元个数
}TSMatrix;

Status CreateSMatrix(TSMatrix *M);//创建稀疏矩阵M
Status TransposeSMatrix(TSMatrix *M, TSMatrix *T);//稀疏矩阵的转置
void outPut(TSMatrix *M);//输出矩阵

int main(int argc, const char * argv[]) {
    // insert code here...
    int res = 0;
    TSMatrix M, T;
    
    res = CreateSMatrix(&M);
    if (res == 1) {
        printf("矩阵生成成功!\n");
    }
    outPut(&M);
    
    printf("稀疏矩阵转制之后\n");
    TransposeSMatrix(&M, &T);
    outPut(&T);
    return 0;
}
Status CreateSMatrix(TSMatrix *M)
{
    int i;
    
    printf("请输入稀疏矩阵的行数：");
    scanf("%d", &M->row);
    printf("请输入稀疏矩阵的列数：");
    scanf("%d", &M->col);
    printf("请输入矩阵的非零元个数:");
    scanf("%d", &M->tn);
    
    printf("输入非零元素的行列下表和数字：");
    for (i = 1; i <= M->tn; i++) {
        scanf("%d", &M->data[i].i);
        scanf("%d", &M->data[i].j);
        scanf("%d", &M->data[i].e);
    }
    
    return OK;
}

Status TransposeSMatrix(TSMatrix *M, TSMatrix *T)
{
    int i, j;
    int q = 1;
    T->row = M->col;
    T->col = M->row;
    T->tn = M->tn;
    
    if (T->tn) {
        for (i = 1; i <= M->col; i++) {
            for (j = 1; j <= M->tn; j++) {
                if (M->data[j].j == i) {
                    T->data[q].i = M->data[j].j;
                    T->data[q].j = M->data[j].i;
                    T->data[q].e = M->data[j].e;
                    q++;
                }
            }
        }
    }
    return OK;
}
void outPut(TSMatrix *M)
{
    int i;
    printf("输出矩阵：\n");
    for (i = 1; i <= M->tn; i++)
        printf("%d %d %d\n", M->data[i].i, M->data[i].j, M->data[i].e);
}
